<template>
  <div class="history-page">
    <div class="page-header">
      <h2 class="page-title">历史订单</h2>
      <p class="page-subtitle">查看已完成的订单记录</p>
    </div>

    <div v-if="!state.orders || state.orders.length === 0" class="empty-state">
      <el-empty description="暂无历史订单">
        <el-button type="primary" @click="$router.push('/home/rest')">
          去下单
        </el-button>
      </el-empty>
    </div>

    <div v-else class="orders-container">
      <el-card
        v-for="order in state.orders"
        :key="order.OrderID"
        class="history-order-card"
        shadow="hover"
      >
        <div class="order-header">
          <div class="order-info">
            <h3 class="order-number">订单号：{{ order.OrderID }}</h3>
            <p class="order-date">{{ new Date(order.OrderDate).toLocaleDateString() }}</p>
          </div>
          <div class="order-total">
            <span class="total-label">总金额</span>
            <span class="total-amount">¥{{ order.TotalPrice }}</span>
          </div>
        </div>

        <div class="order-content">
          <div class="order-basic-info">
            <div class="info-item">
              <span class="info-label">地址：</span>
              <span class="info-value">{{ order.address }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">联系方式：</span>
              <span class="info-value">{{ order.contact }}</span>
            </div>
            <div class="info-item" v-if="order.beizhu">
              <span class="info-label">备注：</span>
              <span class="info-value">{{ order.beizhu }}</span>
            </div>
          </div>

          <div class="order-details">
            <h4 class="details-title">订单详情</h4>
            <div class="details-list">
              <div
                v-for="detail in getOrderDetails(order.OrderID)"
                :key="detail.OrderDetailID"
                class="detail-item"
              >
                <div class="detail-image">
                  <img :src="detail.ImageURL" alt="菜品图片" />
                </div>
                <div class="detail-info">
                  <div class="dish-name">{{ detail.DishName }}</div>
                  <div class="dish-meta">
                    <span class="dish-price">¥{{ detail.Price }}</span>
                    <span class="dish-count">x{{ detail.Count }}</span>
                  </div>
                </div>
                <div class="detail-actions">
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleEvaluate(detail.OrderDetailID)"
                  >
                    评价
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { getHistoryOrdersApi, addCommentsApi } from "@/utils/api";

const state = ref({});

const fetchHistoryOrders = async () => {
  const user_id = JSON.parse(localStorage.getItem("user")).user_id;
  const res = await getHistoryOrdersApi({ user_id });
  state.value = res;
};

fetchHistoryOrders();

// 根据订单ID获取订单详情
const getOrderDetails = (orderId) => {
  if (!state.value.orderDetails) return [];
  return state.value.orderDetails.filter(detail => detail.OrderID === orderId);
};

const handleEvaluate = async (orderDetailID) => {
  // 检查用户是否已登录
  const user = JSON.parse(localStorage.getItem("user"));
  if (!user) {
    alert("请先登录！");
    return;
  }

  // 获取评分和评论内容
  let rating = Number(prompt("请给这道菜打分(1-3分)"));
  let comment = prompt("请给这道菜写点评");

  // 对评分进行验证
  while (isNaN(rating) || rating < 1 || rating > 3) {
    rating = Number(prompt("评分只能是1-3之间的整数，请重新输入"));
  }

  // 对评论内容进行验证
  while (!comment) {
    comment = prompt("评论内容不能为空，请重新输入");
  }

  // 构造评价信息
  const evaluationData = {
    user_id: user.user_id,
    dish_id: orderDetailID,
    rating: rating,
    comment: comment,
  };

  try {
    const res = await addCommentsApi(evaluationData);
    console.log("评价结果：", res);
    alert("评价成功！");
  } catch (error) {
    console.error("评价失败：", error);
    alert("评价失败，请重试");
  }
};
</script>

<style lang="less" scoped>
.history-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 24px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 8px 0;
  }

  .page-subtitle {
    color: #909399;
    margin: 0;
    font-size: 14px;
  }
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 8px;
}

.orders-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.history-order-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;

  :deep(.el-card__body) {
    padding: 0;
  }
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: #fafbfc;
  border-bottom: 1px solid #ebeef5;

  .order-info {
    .order-number {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      margin: 0 0 8px 0;
    }

    .order-date {
      font-size: 14px;
      color: #909399;
      margin: 0;
    }
  }

  .order-total {
    text-align: right;

    .total-label {
      display: block;
      font-size: 14px;
      color: #909399;
      margin-bottom: 4px;
    }

    .total-amount {
      font-size: 20px;
      font-weight: 600;
      color: #f56c6c;
    }
  }
}

.order-content {
  padding: 24px;
}

.order-basic-info {
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f2f5;

  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 12px;

    &:last-child {
      margin-bottom: 0;
    }

    .info-label {
      color: #606266;
      font-size: 14px;
      margin-right: 8px;
      min-width: 80px;
    }

    .info-value {
      color: #303133;
      font-size: 14px;
      flex: 1;
    }
  }
}

.order-details {
  .details-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 16px 0;
  }

  .details-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .detail-item {
    display: flex;
    align-items: center;
    padding: 16px;
    background: #fafbfc;
    border-radius: 8px;
    border: 1px solid #f0f2f5;

    .detail-image {
      width: 80px;
      height: 80px;
      border-radius: 8px;
      overflow: hidden;
      margin-right: 16px;
      flex-shrink: 0;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .detail-info {
      flex: 1;

      .dish-name {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
        margin-bottom: 8px;
      }

      .dish-meta {
        display: flex;
        align-items: center;
        gap: 16px;

        .dish-price {
          font-size: 16px;
          font-weight: 600;
          color: #f56c6c;
        }

        .dish-count {
          font-size: 14px;
          color: #909399;
        }
      }
    }

    .detail-actions {
      flex-shrink: 0;
    }
  }
}

@media (max-width: 768px) {
  .history-page {
    padding: 16px;
  }

  .order-header {
    padding: 16px;
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .order-content {
    padding: 16px;
  }

  .detail-item {
    flex-direction: column;
    text-align: center;

    .detail-image {
      margin-right: 0;
      margin-bottom: 12px;
    }

    .detail-actions {
      margin-top: 12px;

      .el-button {
        width: 100%;
      }
    }
  }
}
</style>
